package org.example.supermarketms.dao;


import lombok.RequiredArgsConstructor;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.example.supermarketms.model.OrderData;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Repository
@RequiredArgsConstructor
public class HBaseDAO {

    private final Connection connection;
    private final TableName tableName;


    public List<OrderData> scanAll() throws IOException {
        Table table = connection.getTable(tableName);
        Scan scan = new Scan();
        ResultScanner scanner = table.getScanner(scan);

        List<OrderData> orders = new ArrayList<>();
        for (Result result : scanner) {
            OrderData order = new OrderData();
            order.setRowkey(Bytes.toString(result.getRow()));

            for (Cell cell : result.listCells()) {
                byte[] qualifierBytes = CellUtil.cloneQualifier(cell);
                String qualifier = new String(qualifierBytes, StandardCharsets.UTF_8); // 关键：UTF-8 解码
                String value = Bytes.toString(CellUtil.cloneValue(cell));

                switch (qualifier) {
                    case "商品名称":
                        order.setGoodsName(value);
                        break;
                    case "商品类别":
                        order.setCategory(value);
                        break;
                    case "商品单价":
                        order.setPrice(Double.parseDouble(value));
                        break;
                    case "购买数量":
                        order.setQuantity(Integer.parseInt(value));
                        break;
                    case "总金额":
                        order.setTotalAmount(Double.parseDouble(value));
                        break;
                    case "折扣金额":
                        order.setDiscount(Double.parseDouble(value));
                        break;
                    case "实际金额":
                        order.setActualAmount(Double.parseDouble(value));
                        break;
                    case "支付方式":
                        order.setPaymentMethod(value);
                        break;
                    case "下单时间":
                        order.setOrderTime(value);
                        break;
                }
            }

            orders.add(order);
        }

        return orders;
    }
}